package com.sky.controller.user;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/addressBook")
@Api(tags = "地址簿相关接口")
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;
    @GetMapping("list")
    @ApiOperation("查询当前登录用户的所有地址信息")
    public Result list(){
       List<AddressBook> addressBook = addressBookService.list();
        return Result.success(addressBook);
    }
    @PostMapping()
    @ApiOperation("新增地址")
    public Result add (@RequestBody AddressBook addressBook ){
        addressBookService.insert(addressBook);
        return Result.success();
    }
    @GetMapping("/{id}")
    @ApiOperation("根据id查询地址")
    public Result getByid(@PathVariable Long id){
        AddressBook addressBook = addressBookService.getByid(id);
        return Result.success(addressBook);
    }
    @PutMapping
    @ApiOperation("根据ID修改地址")
    public Result update(@RequestBody AddressBook addressBook){
        addressBookService.update(addressBook);
        return Result.success();
    }
    @DeleteMapping
    @ApiOperation("根据ID删除地址")
    public Result delete(Long id){
        addressBookService.delete(id);
        return Result.success();

    }
    @PutMapping("default")
    @ApiOperation("设置默认地址")
    public Result setDefault(@RequestBody AddressBook addressBook){
        addressBookService.setDefault(addressBook);
        return Result.success();
    }
    @GetMapping("default")
    @ApiOperation("查询默认地址")
    public Result getDefault(){
        //SQL:select * from address_book where user_id = ? and is_default = 1
        AddressBook addressBook = new AddressBook();
        addressBook.setIsDefault(1);
        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook> list = addressBookService.getDefault(addressBook);

        if (list != null && list.size() == 1) {
            return Result.success(list.get(0));
        }

        return Result.error("没有查询到默认地址");
    }
}
